package cn.com.codes.iteration.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.codes.common.dto.PageModel;
import cn.com.codes.common.util.StringUtils;
import cn.com.codes.framework.app.services.BaseServiceImpl;
import cn.com.codes.framework.security.VisitUser;
import cn.com.codes.framework.security.filter.SecurityContextHolder;
import cn.com.codes.iteration.dto.IterationDto;
import cn.com.codes.iteration.dto.IterationVo;
import cn.com.codes.iteration.service.IterationService;
import cn.com.codes.object.ApiTestScene;
import cn.com.codes.object.BugBaseInfo;
import cn.com.codes.object.IterationBugReal;
import cn.com.codes.object.IterationInterfaceReal;
import cn.com.codes.object.IterationList;
import cn.com.codes.object.IterationOperationHistory;
import cn.com.codes.object.IterationTaskReal;
import cn.com.codes.object.IterationTestcasepackageReal;
import cn.com.codes.object.OtherMission;
import cn.com.codes.object.TestCasePackage;
import cn.com.codes.object.UserTestCasePkg;


public class IterationServiceImpl extends BaseServiceImpl implements IterationService {
	
	
	
	
	@Override
	public void addIterationData(IterationDto dto) {
		// TODO Auto-generated method stub
		this.add(dto.getIterationList());

		
	}

	@Override
	public void updateIterationData(IterationDto dto) {
		IterationList iterationList = this.get(IterationList.class, dto.getIterationList().getIterationId());
		dto.getIterationList().setCreateTime(iterationList.getCreateTime());
		dto.getIterationList().setUpdateTime(new Date());
		if((iterationList.getTaskId()).equals(dto.getIterationList().getTaskId())){
			//更新迭代数据
			updateIterationDifferentOrEqualTaskId(iterationList,dto);
		}else {
			//修改了关联项目，在操作历史记录表，记录下
			addUpdateAssociationProjectRecord(iterationList,dto);
			//更新迭代数据
			updateIterationDifferentOrEqualTaskId(iterationList,dto);
			deleteIterationInfoDiffTaskId(iterationList);

		}

	}

	/** 
	* 方法名:          addUpdateAssociationProjectRecord
	* 方法功能描述:     //修改了关联项目，在操作历史记录表，记录下
	* @param:         
	* @return:        
	* @Author:          
	* @Create Date:   2019年8月14日 下午2:28:18
	*/
	private void addUpdateAssociationProjectRecord(IterationList iterationList,IterationDto dto) {
		IterationOperationHistory iterationOperationHistory = new IterationOperationHistory();
		iterationOperationHistory.setTaskId(dto.getIterationList().getTaskId());
		iterationOperationHistory.setIterationId(iterationList.getIterationId());
		iterationOperationHistory.setUserId(dto.getIterationList().getUserId());
		iterationOperationHistory.setOperationPersonName(dto.getIterationList().getCreatePerson());
		iterationOperationHistory.setName(iterationList.getAssociationProject()+"-->"+dto.getIterationList().getAssociationProject());
		iterationOperationHistory.setOperationTime(new Date());
		iterationOperationHistory.setOperationType("3");//修改了关联项目
		iterationOperationHistory.setOperationHistory("2");//关联项目名称改变
		
		this.saveOrUpdate(iterationOperationHistory);
		
	}

	/** 
	* 方法名:          updateIterationDifferentOrEqualTaskId
	* 方法功能描述:      //更新迭代数据
	* @param:         
	* @return:        
	* @Author:          
	* @Create Date:   2019年8月14日 下午12:27:05
	*/
	private void updateIterationDifferentOrEqualTaskId(IterationList iterationList, IterationDto dto) {
		dto.getIterationList().setStatus("0");
		iterationList.setIterationBagName(dto.getIterationList().getIterationBagName());
		iterationList.setTaskId(dto.getIterationList().getTaskId());
		iterationList.setIterationStatus(dto.getIterationList().getIterationStatus());
		iterationList.setStartTime(dto.getIterationList().getStartTime());
		iterationList.setEndTime(dto.getIterationList().getEndTime());
		iterationList.setNote(dto.getIterationList().getNote());
		iterationList.setPredictStartTime(dto.getIterationList().getPredictStartTime());
		iterationList.setPredictEndTime(dto.getIterationList().getPredictEndTime());
		iterationList.setCreatePerson(dto.getIterationList().getCreatePerson());
		iterationList.setAssociationProject(dto.getIterationList().getAssociationProject());
		this.update(iterationList);
		
	}

	/** 
	* 方法名:          deleteIterationInfoDiffTaskId
	* 方法功能描述:     当修改了关联项目时，删除数据库里面原来的数据
	* @param:         
	* @return:        
	* @Author:          
	* @Create Date:   2019年8月13日 下午5:18:09
	*/
	private void deleteIterationInfoDiffTaskId(IterationList iterationList) {
		//删除t_iteration_bug_real的信息
				this.executeUpdateByHql(" delete from IterationBugReal where iterationId = ? ", new Object[]{iterationList.getIterationId()});
				
				//删除t_iteration_task_real的信息
				this.executeUpdateByHql(" delete from IterationTaskReal where iterationId = ? ", new Object[]{iterationList.getIterationId()});
				
				//删除t_iteration_testcasepackage_real的信息
				this.executeUpdateByHql(" delete from IterationTestcasepackageReal where iterationId = ? ", new Object[]{iterationList.getIterationId()});
				
	}

	/* (非 Javadoc)   
	* <p>Title: getBugTaskTestcaseInfo</p>   
	* <p>Description: </p>   
	* @param dto   
	* @see cn.com.codes.iteration.service.IterationService#getBugTaskTestcaseInfo(cn.com.codes.iteration.dto.IterationDto)   
	*/
	@SuppressWarnings("unchecked")
	@Override
	public void getBugTaskTestcaseInfo(IterationDto dto) {
		// TODO Auto-generated method stub
		String iteraId = dto.getIterationList().getIterationId();
		String status = "0";
		String sql1= " SELECT bu.BUGDESC AS descr,bu.BUGCARDID AS bugCId "
				+ "FROM t_iteration_list it LEFT JOIN t_iteration_bug_real itb "
				+ "ON it.iteration_id = itb.iteration_id LEFT JOIN t_bugbaseinfo bu "
				+ "ON itb.bug_card_id = bu.BUGCARDID WHERE it.iteration_id='"+iteraId+"' AND it.status='"+status+"' ";
		 List<Map<String, Object>> bugMaps = this.findBySqlByJDBC(sql1);
		if(bugMaps.size() > 0){
			for (int i = 0; i < bugMaps.size(); i++) {
				Map<String, Object> map = bugMaps.get(i);
				Long bugCId = (Long)map.get("bugCId");
				if(bugCId!=null){
					dto.setBaseInfos(bugMaps);
				}else {
					dto.setBaseInfos(null);
				}
			}
		}else {
			dto.setBaseInfos(null);
		}
		
		String sql2 = " SELECT omi.mission_name AS missName,omi.mission_id AS missionId,omi.description AS descp "
				+ "FROM t_iteration_list it LEFT JOIN t_iteration_task_real itt "
				+ "ON it.iteration_id = itt.iteration_id LEFT JOIN t_other_mission omi "
				+ "ON itt.mission_id = omi.mission_id WHERE it.iteration_id='"+iteraId+"' "
				+ "AND it.status='"+status+"'";
		List<Map<String,Object>> otherMisList = this.findBySqlByJDBC(sql2);
		if(otherMisList.size() > 0){
			for (int i = 0; i < otherMisList.size(); i++) {
				Map<String, Object> map = otherMisList.get(i);
				String missionId = (String)map.get("missionId");
				if(missionId!=null){
					dto.setMissions(otherMisList);
				}else {
					dto.setMissions(null);
				}
			}
			
		}else {
			dto.setMissions(null);
		}
		
		String sql3 ="SELECT tcs.package_name AS packName,tcs.executor AS executors,tcs.id AS caseId "
				+ "FROM t_iteration_list it LEFT JOIN t_iteration_testcasepackage_real itc "
				+ "ON it.iteration_id = itc.iteration_id LEFT JOIN t_testcasepackage tcs "
				+ "ON tcs.id = itc.package_id WHERE it.iteration_id='"+iteraId+"' "
				+ "AND it.status='"+status+"' ";
		List<Map<String,Object>> testCaseList = this.findBySqlByJDBC(sql3);
		if(testCaseList.size() > 0){
			for (int i = 0; i < testCaseList.size(); i++) {
				Map<String, Object> map = testCaseList.get(i);
				String caseId = (String)map.get("caseId");
				if(caseId!=null){
					dto.setCasePackages(testCaseList);
				}else {
					dto.setCasePackages(null);
				}
			}
			
		}else {
			dto.setCasePackages(null);
		}
	}

	/* (非 Javadoc)   
	* <p>Title: deleteIterationAboutInfo</p>   
	* <p>Description: </p>   
	* @param dto   
	* @see cn.com.codes.iteration.service.IterationService#deleteIterationAboutInfo(cn.com.codes.iteration.dto.IterationDto)   
	*/
	@Override
	public void deleteIterationAboutInfo(IterationDto dto) {
		//删除t_iteration_bug_real的信息
		this.executeUpdateByHql(" delete from IterationBugReal where iterationId = ? ", new Object[]{dto.getIterationList().getIterationId()});
		
		//删除t_iteration_task_real的信息
		this.executeUpdateByHql(" delete from IterationTaskReal where iterationId = ? ", new Object[]{dto.getIterationList().getIterationId()});
		
		//删除t_iteration_testcasepackage_real的信息
		this.executeUpdateByHql(" delete from IterationTestcasepackageReal where iterationId = ? ", new Object[]{dto.getIterationList().getIterationId()});
		
		//删除t_iteration_list的信息
		this.executeUpdateByHql(" delete from IterationList where iterationId = ? ", new Object[]{dto.getIterationList().getIterationId()});
	}

	/* (非 Javadoc)   
	* <p>Title: bugDetail</p>   
	* <p>Description: </p>   
	* @param dto   
	* @see cn.com.codes.iteration.service.IterationService#bugDetail(cn.com.codes.iteration.dto.IterationDto)   
	*/
	@SuppressWarnings("unchecked")
	@Override
	public void bugDetail(IterationDto dto) {
		String sqlBug = " SELECT itbs.BUGDESC AS bugDesc,itbs.BUGCARDID AS bugId,itbs.TASK_ID AS taskId, "
				+ "itbs.BUGTYPE AS bugTypeId,itbs.CURRENT_STATE AS currStateId,itbs.MODULEID AS moduleId, "
				+ "itbs.BUGLEVEL AS bugGradeId,itbs.GENERATECAUSE AS geneCauseId,itbs.DISCOVER_VER AS bugReptVer, "
				+ "itbs.PRI AS priId,itbs.TEST_OWNER AS testOwnerId, "
				+ "itbs.DEV_OWNER AS devOwnerId,itbs.BUGDISVDATE AS reptDate "
				+ "FROM t_iteration_list it INNER JOIN t_iteration_bug_real itb "
				+ "ON it.iteration_id = itb.iteration_id INNER JOIN t_bugbaseinfo itbs ON itbs.BUGCARDID = itb.bug_card_id "
				+ "WHERE it.iteration_id='"+dto.getIterationList().getIterationId()+"' ";
		
		PageModel pageModel = dto.getPageModel();
		pageModel.setQueryHql(sqlBug);
		pageModel.setPageNo(dto.getPageNo());
		pageModel.setPageSize(dto.getPageSize());
		
		super.getJdbcTemplateWrapper().fillPageModelData(pageModel,null, "BUGCARDID");
		super.getJdbcTemplateWrapper().converDbColumnName2ObjectPropName((List<Map<String, Object>>) dto.getPageModel().getRows());

	}

	/* (非 Javadoc)   
	* <p>Title: batchSaveTestCasePackage</p>   
	* <p>Description: </p>   
	* @param iterationTestcaseList   
	* @see cn.com.codes.iteration.service.IterationService#batchSaveTestCasePackage(java.util.ArrayList)   
	*/
	@Override
	public void batchSaveTestCasePackage(
			List<IterationTestcasepackageReal> iterationTestcaseList) {
		String flag="0";
		this.batchSaveIterOperHisTestCase(iterationTestcaseList,flag);
		this.batchSaveOrUpdate(iterationTestcaseList);
	}

	/** 
	* 方法名:          batchSaveIterOperHisTestCase
	* 方法功能描述:     保存项目测试包的数据
	* @param:         
	* @return:        
	* @Author:          
	* @Create Date:   2019年2月28日 上午10:11:45
	*/
	@SuppressWarnings("unchecked")
	private void batchSaveIterOperHisTestCase(List<IterationTestcasepackageReal> iterationTestcaseList,String flag) {
		String userId = SecurityContextHolder.getContext().getVisit().getUserInfo(VisitUser.class).getId();
		String userName = SecurityContextHolder.getContext().getVisit().getUserInfo(VisitUser.class).getName();
		List<IterationOperationHistory> operHisList = new ArrayList<IterationOperationHistory>();
		if(null!=iterationTestcaseList&&iterationTestcaseList.size()>0){
			for (int i = 0; i < iterationTestcaseList.size(); i++) {
				IterationOperationHistory operationHistory = new IterationOperationHistory();
				String packageId = iterationTestcaseList.get(i).getPackageId();
				List<TestCasePackage> testCasePackages = this.findByHqlRefresh("from TestCasePackage tc where tc.packageId=?", packageId);
						
				operationHistory.setPackageId(testCasePackages.get(0).getPackageId());
				operationHistory.setName(testCasePackages.get(0).getPackageName());
				operationHistory.setOperationTime(new Date());
				operationHistory.setOperationType("2");
				operationHistory.setUserId(userId);
				operationHistory.setIterationId(iterationTestcaseList.get(i).getIterationId());
				operationHistory.setOperationPersonName(userName);
				if("0".equals(flag)){
					operationHistory.setOperationHistory("0");//0增加，1删除
				}else {
					operationHistory.setOperationHistory("1");
				}
				
				operHisList.add(operationHistory);
			}
		}
		this.batchSaveOrUpdate(operHisList);
	}

	/* (非 Javadoc)   
	* <p>Title: TestCaseDetail</p>   
	* <p>Description: </p>   
	* @param dto
	* @return   
	* @see cn.com.codes.iteration.service.IterationService#TestCaseDetail(cn.com.codes.iteration.dto.IterationDto)   
	*/
	@SuppressWarnings("unchecked")
	@Override
	public void TestCaseDetail(IterationDto dto) {
		String sqlCase = " SELECT tca.id AS packageId,tca.taskId AS taskId, "
				+ "tca.package_name AS packageName,tca.exec_environment AS execEnvironment, "
				+ "tca.executor AS executor,tca.REMARK AS remark,tca.exe_count as exeCount,tca.not_exe_count as notExeCount  "
				+ "FROM t_iteration_list it INNER JOIN t_iteration_testcasepackage_real itt "
				+ "ON it.iteration_id = itt.iteration_id INNER JOIN t_testcasepackage tca "
				+ "ON tca.id = itt.package_id "
				+ "WHERE it.iteration_id = '"+dto.getIterationList().getIterationId()+"' ";
		

		PageModel pageModel = dto.getPageModel();
		pageModel.setQueryHql(sqlCase);
		pageModel.setPageNo(dto.getPageNo());
		pageModel.setPageSize(dto.getPageSize());
		
		super.getJdbcTemplateWrapper().fillPageModelData(pageModel,null, "id");
//		//查询用例测试包的信息
//		searchTestCasePackageInfo(dto);
		super.getJdbcTemplateWrapper().converDbColumnName2ObjectPropName((List<Map<String, Object>>) dto.getPageModel().getRows());
	
	}

	/* (非 Javadoc)   
	* <p>Title: batchSaveIteraTask</p>   
	* <p>Description: </p>   
	* @param iterationTaskRealList   
	* @see cn.com.codes.iteration.service.IterationService#batchSaveIteraTask(java.util.ArrayList)   
	*/
	@Override
	public void batchSaveIteraTask(
			List<IterationTaskReal> iterationTaskRealList) {
		String flag="0";
		this.batchSaveIterOperHisTask(iterationTaskRealList,flag);
		this.batchSaveOrUpdate(iterationTaskRealList);
	}

	/** 
	* 方法名:          batchSaveIterOperHisTask
	* 方法功能描述:    
	* @param:         
	* @return:        
	* @Author:        your name
	* @Create Date:   2019年2月27日 下午3:27:16
	*/
	@SuppressWarnings("unchecked")
	private void batchSaveIterOperHisTask(List<IterationTaskReal> iterationTaskRealList, String flag) {
		String userId = SecurityContextHolder.getContext().getVisit().getUserInfo(VisitUser.class).getId();
		String userName = SecurityContextHolder.getContext().getVisit().getUserInfo(VisitUser.class).getName();
		List<IterationOperationHistory> operHisList = new ArrayList<IterationOperationHistory>();
		if(null!=iterationTaskRealList&&iterationTaskRealList.size()>0){
			for (int i = 0; i < iterationTaskRealList.size(); i++) {
				IterationOperationHistory operationHistory = new IterationOperationHistory();
				String missionId = iterationTaskRealList.get(i).getMissionId();
				List<OtherMission> otherMissions = this.findByHqlRefresh("from OtherMission om where om.missionId=?", missionId);
						
				operationHistory.setMissionId(otherMissions.get(0).getMissionId());
				operationHistory.setName(otherMissions.get(0).getMissionName());
				operationHistory.setOperationTime(new Date());
				operationHistory.setOperationType("1");
				operationHistory.setUserId(userId);
				operationHistory.setIterationId(iterationTaskRealList.get(i).getIterationId());
				operationHistory.setOperationPersonName(userName);
				if("0".equals(flag)){
					operationHistory.setOperationHistory("0");//0增加，1删除
				}else {
					operationHistory.setOperationHistory("1");
				}
				
				operHisList.add(operationHistory);
			}
		}
		this.batchSaveOrUpdate(operHisList);
	}

	/* (非 Javadoc)   
	* <p>Title: TaskDetail</p>   
	* <p>Description: </p>   
	* @param dto
	* @return   
	* @see cn.com.codes.iteration.service.IterationService#TaskDetail(cn.com.codes.iteration.dto.IterationDto)   
	*/
	@SuppressWarnings("unchecked")
	@Override
	public void TaskDetail(IterationDto dto) {
		String sqlTask = " SELECT tm.mission_id AS missionId,tm.mission_name AS missionName, "
				+ "tm.project_id AS projectId,tm.charge_person_id AS chargePersonId, "
				+ "tm.actual_workload AS actualWorkload,tm.description AS description, "
				+ "tm.completion_degree AS completionDegree,tm.status AS status,tm.real_start_time AS realStartTime, "
				+ "tm.mission_category AS missionCategory,tm.emergency_degree AS emergencyDegree,tm.difficulty_degree AS difficultyDegree, "
				+ "tm.standard_workload AS standardWorkload,tm.predict_start_time AS predictStartTime,tm.predict_end_time AS predictEndTime,tm.create_user_id AS createUserId, tm.create_time AS createTime "
				+ "FROM t_iteration_list it INNER JOIN t_iteration_task_real ita "
				+ "ON it.iteration_id = ita.iteration_id INNER JOIN t_other_mission tm "
				+ "ON tm.mission_id = ita.mission_id WHERE it.iteration_id = '"+dto.getIterationList().getIterationId()+"' ";
		
		PageModel pageModel = dto.getPageModel();
		pageModel.setQueryHql(sqlTask);
		pageModel.setPageNo(dto.getPageNo());
		pageModel.setPageSize(dto.getPageSize());
		
		super.getJdbcTemplateWrapper().fillPageModelData(pageModel,null, "mission_id");
		super.getJdbcTemplateWrapper().converDbColumnName2ObjectPropName((List<Map<String, Object>>) dto.getPageModel().getRows());
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void interfaceDetail(IterationDto dto) {
		String sqlInterface = " SELECT ti.scene_id AS sceneId,ti.scene_name AS sceneName,"
				+ "ti.task_id AS taskId,ti.plan_start_time AS planStartTime,"
				+ "ti.plan_end_time AS planEndTime,ti.actual_start_time AS actualStartTime,"
				+ "ti.executor AS executor,ti.exec_environment AS execEnvironment,"
				+ "ti.exec_version AS execVersion,ti.continued AS continued,"
				+ "ti.exec_cnt AS execCnt,ti.unexec_cnt AS unexecCnt,"
				+ "ti.creator_id AS creatorId,ti.updator_id AS updatorId,"
				+ "ti.create_time AS createTime,ti.update_time AS updateTime,"
				+ "ti.execution_order AS executionOrder "
				+ "FROM t_iteration_list it INNER JOIN t_iteration_interface_real ita "
				+ "ON it.iteration_id = ita.iteration_id INNER JOIN t_api_test_scene ti "
				+ "ON ti.scene_id = ita.interface_id "
				+ "WHERE it.iteration_id = '"+dto.getIterationList().getIterationId()+"'";
		
		PageModel pageModel = dto.getPageModel();
		pageModel.setQueryHql(sqlInterface);
		pageModel.setPageNo(dto.getPageNo());
		pageModel.setPageSize(dto.getPageSize());
		
		super.getJdbcTemplateWrapper().fillPageModelData(pageModel,null, "scene_id");
		super.getJdbcTemplateWrapper().converDbColumnName2ObjectPropName((List<Map<String, Object>>) dto.getPageModel().getRows());
	}

	/* (非 Javadoc)   
	* <p>Title: batchSaveIteraBug</p>   
	* <p>Description: </p>   
	* @param iterationBugReals   
	* @see cn.com.codes.iteration.service.IterationService#batchSaveIteraBug(java.util.List)   
	*/
	@Override
	public void batchSaveIteraBug(List<IterationBugReal> iterationBugReals) {
		// TODO Auto-generated method stub
		String flag="0";
		this.batchSaveIterationOperHis(iterationBugReals,flag);
		this.batchSaveOrUpdate(iterationBugReals);
	}

	/** 
	* 方法名:          batchSaveIterationOperHis
	* 方法功能描述:    
	* @param:         
	* @return:        
	* @Author:        your name
	* @Create Date:   2019年2月26日 上午10:58:42
	*/
	@SuppressWarnings("unchecked")
	private void batchSaveIterationOperHis(List<IterationBugReal> iterationBugReals,String flg) {
		
		String userId = SecurityContextHolder.getContext().getVisit().getUserInfo(VisitUser.class).getId();
		String userName = SecurityContextHolder.getContext().getVisit().getUserInfo(VisitUser.class).getName();
		List<IterationOperationHistory> operHisList = new ArrayList<IterationOperationHistory>();
		if(null!=iterationBugReals&&iterationBugReals.size()>0){
			for (int i = 0; i < iterationBugReals.size(); i++) {
				IterationOperationHistory operationHistory = new IterationOperationHistory();
				String bugCardId = iterationBugReals.get(i).getBugCardId();
				List<BugBaseInfo> bugBaseLists = this.findByHqlRefresh("from BugBaseInfo bu where bu.bugId=?", Long.valueOf(bugCardId));
						
				operationHistory.setTaskId(bugBaseLists.get(0).getTaskId());
				operationHistory.setBugId(String.valueOf(bugBaseLists.get(0).getBugId()));
				operationHistory.setName(bugBaseLists.get(0).getBugDesc());
				operationHistory.setOperationTime(new Date());
				operationHistory.setOperationType("0");
				operationHistory.setUserId(userId);
				operationHistory.setOperationPersonName(userName);
				if("0".equals(flg)){
					operationHistory.setOperationHistory("0");//0增加，1删除
				}else {
					operationHistory.setOperationHistory("1");
				}
				operationHistory.setIterationId(iterationBugReals.get(i).getIterationId());
				
				operHisList.add(operationHistory);
			}
		}
		this.batchSaveOrUpdate(operHisList);
	}

	/* (非 Javadoc)   
	* <p>Title: differentPersonWatchIterationDataInfo</p>   
	* <p>Description: </p>   
	* @param dto
	* @return   
	* @see cn.com.codes.iteration.service.IterationService#differentPersonWatchIterationDataInfo(cn.com.codes.iteration.dto.IterationDto)   
	*/
	@SuppressWarnings("unchecked")
	@Override
	public List<IterationVo> differentPersonWatchIterationDataInfo(IterationDto dto) {
		IterationList iterationList = dto.getIterationList();
		String userId = iterationList.getUserId();
		String loginName = SecurityContextHolder.getContext().getVisit().getUserInfo(VisitUser.class).getLoginName();
		HashMap<String,Object> hashMap = new HashMap<String,Object>();
//		PageModel pageModel = new PageModel();
		StringBuffer buffer = new StringBuffer();
		buffer.append(" select  * from ( ") ;
		buffer.append(" SELECT it.* FROM t_iteration_list it ,(SELECT TASKID as project_id ,PRO_NAME as project_name FROM t_single_test_task where filter_flag <>1 ");
		if(null!=iterationList){
			if(!StringUtils.isNullOrEmpty(userId)){
				buffer.append(" and (CREATE_ID=:createId");
				buffer.append(" or psm_id=:psmId) and status_flg!=4 ");
				hashMap.put("createId", userId);
				hashMap.put("psmId", userId);
				
				buffer.append(" union SELECT distinct pro.taskid as project_id, pro.pro_name as project_name  "
						+ " FROM t_single_test_task pro ,(SELECT om.* FROM t_other_mission om "
						+ " join t_user_other_mission uom on om.mission_id=uom.mission_id "
						+ " and om.project_id is not null");
				
				buffer.append(" and uom.user_id=:userId ");
				hashMap.put("userId", userId);
				
				buffer.append(" union SELECT om.* FROM t_other_mission om join t_concern_other_mission com "
						+ " on om.mission_id=com.mission_id and om.project_id is not null");
				
				buffer.append(" and com.user_id=:userId1");
				hashMap.put("userId1", userId);
				
				buffer.append(" union SELECT om.* FROM t_other_mission om where");
				buffer.append(" om.create_user_id=:createUserId");
				hashMap.put("createUserId", loginName);
				
				buffer.append(" and om.project_id is not null) proTask");
				
				buffer.append(" where pro.taskid = proTask.project_id and pro.status_flg<>4 "
						+ " union "
						+ " SELECT distinct t.taskid as project_id , t.PRO_NAME as project_name "
						+ " FROM t_single_test_task t join t_task_useactor uat on t.taskid=uat.taskid "
						+ " and uat.is_enable=1 and t.status_flg<>4 ");
				buffer.append(" and uat.userid=:userId2 ");
				hashMap.put("userId2", userId);

				buffer.append(" ) mytask where it.iteration_id is not null ");

				buffer.append(" and (mytask.project_id = it.task_id ) ");

			}
		}
		
		
		buffer.append(" union SELECT it1.* FROM t_iteration_list  it1 where (it1.task_id is null  or it1.task_id ='')");
		buffer.append(" and it1.user_id=:userId4 ");
		buffer.append(   ")  allMyIt order by allMyIt.create_time desc ");
		hashMap.put("userId4", userId);
		 	int totalRows = this.getJdbcTemplateWrapper().getResultCountWithValuesMap(buffer.toString(),
				 "*", hashMap);
		 	dto.setTotal(totalRows);
		 	if(totalRows>0) {
			    List<IterationVo> iterationVos = this.getJdbcTemplateWrapper().queryAllMatchListWithParaMap(buffer.toString(), IterationVo.class, hashMap, dto.getPageNo(), dto.getPageSize(), "*");
			    return iterationVos;
		 	}else {
		 		return null;
		 	}
		 	

	}
	
	
	@SuppressWarnings("unchecked")
	@Override
	public List<IterationVo> differentPersonWatchIterationDataInfoWithParams(IterationDto dto) {
		IterationList iterationList = dto.getIterationList();
		String userId = iterationList.getUserId();
		String loginName = SecurityContextHolder.getContext().getVisit().getUserInfo(VisitUser.class).getLoginName();
		HashMap<String,Object> hashMap = new HashMap<String,Object>();
		StringBuffer buffer = new StringBuffer();
		buffer.append(" SELECT allIterations.* FROM (SELECT it.* FROM t_iteration_list it ,(SELECT TASKID as project_id ,PRO_NAME as project_name FROM t_single_test_task where filter_flag <>1 ");
		if(null!=iterationList){
			if(!StringUtils.isNullOrEmpty(userId)){
				buffer.append(" and (CREATE_ID=:createId");
				buffer.append(" or psm_id=:psmId) and status_flg!=4 ");
				hashMap.put("createId", userId);
				hashMap.put("psmId", userId);
				
				buffer.append(" union SELECT distinct pro.taskid as project_id, pro.pro_name as project_name "
						+ " FROM t_single_test_task pro ,(SELECT om.* FROM t_other_mission om "
						+ " join t_user_other_mission uom on om.mission_id=uom.mission_id "
						+ " and om.project_id is not null");
				
				buffer.append(" and uom.user_id=:userId ");
				hashMap.put("userId", userId);
				
				buffer.append(" union SELECT om.* FROM t_other_mission om join t_concern_other_mission com "
						+ " on om.mission_id=com.mission_id and om.project_id is not null");
				
				buffer.append(" and com.user_id=:userId1");
				hashMap.put("userId1", userId);
				
				buffer.append(" union SELECT om.* FROM t_other_mission om where");
				buffer.append(" om.create_user_id=:createUserId");
				hashMap.put("createUserId", loginName);
				
				buffer.append(" and om.project_id is not null) proTask");
				
				buffer.append(" where 	pro.taskid = proTask.project_id  and pro.status_flg!=4 "
						+ " union "
						+ " SELECT distinct t.taskid as project_id , t.PRO_NAME as project_name "
						+ " FROM t_single_test_task t join t_task_useactor uat on t.taskid=uat.taskid "
						+ " and uat.is_enable=1 and t.status_flg!=4");
				buffer.append(" and uat.userid=:userId2 ");
				hashMap.put("userId2", userId);

				buffer.append(" ) mytask where it.iteration_id is not null ");
				buffer.append(" and mytask.project_id = it.task_id ");
			}
		}
		buffer.append(" union SELECT it1.* FROM t_iteration_list  it1 where (it1.task_id is null  or it1.task_id ='') ");
		buffer.append(" and it1.user_id=:userId4 ) allIterations where allIterations.iteration_id is not null ");
		hashMap.put("userId4", userId);
		if(!StringUtils.isNullOrEmpty(iterationList.getCreatePerson())){
			buffer.append(" and allIterations.create_person =:create_person1");
			hashMap.put("create_person1", iterationList.getCreatePerson());
		}
		if(!StringUtils.isNullOrEmpty(iterationList.getIterationBagName())){
			buffer.append(" and allIterations.iteration_bag_name like :iteration_bag_name1");
			hashMap.put("iteration_bag_name1", "%"+iterationList.getIterationBagName()+"%");
		}
		if(!StringUtils.isNullOrEmpty(iterationList.getAssociationProject())){
			buffer.append(" and allIterations.association_project =:association_project1");
			hashMap.put("association_project1", iterationList.getAssociationProject());
		}
		if(!StringUtils.isNullOrEmpty(iterationList.getIterationId())){
			buffer.append(" and allIterations.iteration_id =:iteration_id1");
			hashMap.put("iteration_id1", iterationList.getIterationId());
		}
		
		buffer.append(" order by allIterations.create_time desc ");
		int totalRows = this.getJdbcTemplateWrapper().getResultCountWithValuesMap(buffer.toString(),
				 "*", hashMap);
		 	dto.setTotal(totalRows);
		 	if(totalRows>0) {
		 		List<IterationVo> iterationVos = this.getJdbcTemplateWrapper().queryAllMatchListWithParaMap(buffer.toString(), IterationVo.class, hashMap, dto.getPageNo(), dto.getPageSize(), "it.iteration_id");
		 		return iterationVos;
		 	}else {
		 		return null;
		 	}

	}

	/* (非 Javadoc)   
	* <p>Title: searchTestCasePackageInfo</p>   
	* <p>Description: </p>   
	* @param packageId
	* @return   
	* @see cn.com.codes.iteration.service.IterationService#searchTestCasePackageInfo(java.lang.String)   
	*/
	@Override
	public List<UserTestCasePkg> searchTestCasePackageInfo(String packageId) {
		List<UserTestCasePkg> userTestLists = this.findByProperties(UserTestCasePkg.class, new String[] {"packageId"}, new Object[]{packageId});
		if(null!=userTestLists&&userTestLists.size()>0){
			return userTestLists;
		}
		return new ArrayList<UserTestCasePkg>();
	}

	/* (非 Javadoc)   
	* <p>Title: iterHisRecord</p>   
	* <p>Description: </p>   
	* @param dto   
	* @see cn.com.codes.iteration.service.IterationService#iterHisRecord(cn.com.codes.iteration.dto.IterationDto)   
	*/
	@SuppressWarnings("unchecked")
	@Override
	public List<IterationOperationHistory> iterHisRecord(IterationDto dto) {
		StringBuffer buffer = new StringBuffer();
		Map<String,Object> map = new HashMap<String, Object>();
		buffer.append(" select * from t_iteration_operation_history ts ");
		if(null!=dto.getIterationList()){
			if(!StringUtils.isNullOrEmpty(dto.getIterationList().getIterationId())){
				buffer.append(" WHERE ts.iteration_id = :iteration_id ");
				map.put("iteration_id", dto.getIterationList().getIterationId());
			}
		}
		
		int totalRows = super.getJdbcTemplateWrapper().getResultCountWithValuesMap(buffer.toString(), "*", map);
		dto.setTotal(totalRows);
	 	if(totalRows>0) {
	 		List<IterationOperationHistory> iterHisLists = super.getJdbcTemplateWrapper().queryAllMatchListWithParaMap(buffer.toString(), IterationOperationHistory.class, map, dto.getPageNo(), dto.getPageSize(), "ts.id");
	 		return iterHisLists;
	 	}else{
	 		return null;
	 	}
		
	}

	/* (非 Javadoc)   
	* <p>Title: fromDeletebatchSaveIterationOperHis</p>   
	* <p>Description: </p>   
	* @param bugLists   
	* @see cn.com.codes.iteration.service.IterationService#fromDeletebatchSaveIterationOperHis(java.util.List)   
	*/
	@Override
	public void fromDeletebatchSaveIterationOperHis(
			List<IterationBugReal> bugLists) {
		// TODO Auto-generated method stub
		String flags="1";
		this.batchSaveIterationOperHis(bugLists,flags);
	}

	/* (非 Javadoc)   
	* <p>Title: fromDeletebatchSaveIterTaskOperHis</p>   
	* <p>Description: </p>   
	* @param taskReals   
	* @see cn.com.codes.iteration.service.IterationService#fromDeletebatchSaveIterTaskOperHis(java.util.List)   
	*/
	@Override
	public void fromDeletebatchSaveIterTaskOperHis(
			List<IterationTaskReal> taskReals) {
		// TODO Auto-generated method stub
		String flags="1";
		this.batchSaveIterTaskOperHis(taskReals,flags);
	}

	/** 
	* 方法名:          batchSaveIterTaskOperHis
	* 方法功能描述:      保存删除的任务信息
	* @param:         
	* @return:        
	* @Author:          
	* @Create Date:   2019年2月27日 下午4:48:27
	*/
	@SuppressWarnings("unchecked")
	private void batchSaveIterTaskOperHis(List<IterationTaskReal> taskReals,String flags) {
		String userId = SecurityContextHolder.getContext().getVisit().getUserInfo(VisitUser.class).getId();
		String userName = SecurityContextHolder.getContext().getVisit().getUserInfo(VisitUser.class).getName();
		List<IterationOperationHistory> operHisLists = new ArrayList<IterationOperationHistory>();
		if(null!=taskReals&&taskReals.size()>0){
			for (int i = 0; i < taskReals.size(); i++) {
				IterationOperationHistory operationHistory = new IterationOperationHistory();
				String missionId = taskReals.get(i).getMissionId();
				List<OtherMission> missions = this.findByHqlRefresh("from OtherMission om where om.missionId=?", missionId);
						
				operationHistory.setMissionId(missions.get(0).getMissionId());
				operationHistory.setName(missions.get(0).getMissionName());
				operationHistory.setOperationTime(new Date());
				operationHistory.setOperationType("1");
				operationHistory.setUserId(userId);
				operationHistory.setIterationId(taskReals.get(i).getIterationId());
				operationHistory.setOperationPersonName(userName);
				if("0".equals(flags)){
					operationHistory.setOperationHistory("0");//0增加，1删除
				}else {
					operationHistory.setOperationHistory("1");
				}
				
				operHisLists.add(operationHistory);
			}
		}
		this.batchSaveOrUpdate(operHisLists);
	}

	/* (非 Javadoc)   
	* <p>Title: fromDeletebatchSaveIterTestCaseOperHis</p>   
	* <p>Description: </p>   
	* @param teIterationTestcasepackageReals   
	* @see cn.com.codes.iteration.service.IterationService#fromDeletebatchSaveIterTestCaseOperHis(java.util.List)   
	*/
	@Override
	public void fromDeletebatchSaveIterTestCaseOperHis(
			List<IterationTestcasepackageReal> teIterationTestcasepackageReals) {
		// TODO Auto-generated method stub
		String flags="1";
		this.batchSaveIterOperHisTestCase(teIterationTestcasepackageReals,flags);
	}

	@Override
	public void batchSaveIteraInterface(
			List<IterationInterfaceReal> iterationInterfaceReals) {
		String flag="0";
		this.batchSaveIterOperHisInterface(iterationInterfaceReals,flag);
		this.batchSaveOrUpdate(iterationInterfaceReals);
	}

	@SuppressWarnings("unchecked")
	private void batchSaveIterOperHisInterface(
			List<IterationInterfaceReal> iterationInterfaceReals, String flag) {
		String userId = SecurityContextHolder.getContext().getVisit().getUserInfo(VisitUser.class).getId();
		String userName = SecurityContextHolder.getContext().getVisit().getUserInfo(VisitUser.class).getName();
		List<IterationOperationHistory> operHisLists = new ArrayList<IterationOperationHistory>();
		if(null!=iterationInterfaceReals&&iterationInterfaceReals.size()>0){
			for (int i = 0; i < iterationInterfaceReals.size(); i++) {
				IterationOperationHistory operationHistory = new IterationOperationHistory();
				String interfaceId = iterationInterfaceReals.get(i).getInterfaceId();
				List<ApiTestScene> apiTestScenes = this.findByHqlRefresh("from ApiTestScene ai where ai.sceneId=?", interfaceId);
						
				operationHistory.setInterfaceId(apiTestScenes.get(0).getSceneId());
				operationHistory.setName(apiTestScenes.get(0).getSceneName());
				operationHistory.setOperationTime(new Date());
				operationHistory.setOperationType("4");
				operationHistory.setUserId(userId);
				operationHistory.setIterationId(iterationInterfaceReals.get(i).getIterationId());
				operationHistory.setOperationPersonName(userName);
				if("0".equals(flag)){
					operationHistory.setOperationHistory("0");//0增加，1删除
				}else {
					operationHistory.setOperationHistory("1");
				}
				
				operHisLists.add(operationHistory);
			}
		}
		this.batchSaveOrUpdate(operHisLists);
		
	}

	@Override
	public void fromDeletebatchSaveIterInterfaceOperHis(
			List<IterationInterfaceReal> iterationInterfaceReals) {
		String flags="1";
		this.batchSaveIterOperHisInterface(iterationInterfaceReals, flags);
		
	}

	@Override
	public void sumbitBugDetail(IterationDto dto) {
		String sqlBug = " SELECT itbs.BUGDESC AS bugDesc,itbs.BUGCARDID AS bugId,itbs.TASK_ID AS taskId, "
				+ "itbs.BUGTYPE AS bugTypeId,itbs.CURRENT_STATE AS currStateId,itbs.MODULEID AS moduleId, "
				+ "itbs.BUGLEVEL AS bugGradeId,itbs.GENERATECAUSE AS geneCauseId,itbs.DISCOVER_VER AS bugReptVer, "
				+ "itbs.PRI AS priId,itbs.TEST_OWNER AS testOwnerId, "
				+ "itbs.DEV_OWNER AS devOwnerId,itbs.BUGDISVDATE AS reptDate "
				+ "FROM t_iteration_list it INNER JOIN t_iteration_submit_bug_real itb "
				+ "ON it.iteration_id = itb.iteration_id INNER JOIN t_bugbaseinfo itbs ON itbs.BUGCARDID = itb.bug_id "
				+ "WHERE it.iteration_id='"+dto.getIterationList().getIterationId()+"' ";
		
		PageModel pageModel = dto.getPageModel();
		pageModel.setQueryHql(sqlBug);
		pageModel.setPageNo(dto.getPageNo());
		pageModel.setPageSize(dto.getPageSize());
		
		super.getJdbcTemplateWrapper().fillPageModelData(pageModel,null, "BUGID");
		super.getJdbcTemplateWrapper().converDbColumnName2ObjectPropName((List<Map<String, Object>>) dto.getPageModel().getRows());
		
	}

}
